package com.gary.security.repository.impl;

import com.gary.core.repository.DefaultRepositoryImpl;
import com.gary.security.AuthenticationHelper;
import com.gary.security.cache.AcegiCacheManager;
import com.gary.security.entity.Resc;
import com.gary.security.model.RescInfo;
import com.gary.security.model.resource.Resource;
import com.gary.security.model.resource.ResourceDetails;
import com.gary.security.repository.RescRepository;

import org.apache.commons.lang.StringUtils;

import org.springframework.security.GrantedAuthority;


/**
 * @author Lingo.
 * @since 2007年08月18日 下午 20时19分00秒578
 */
public class RescRepositoryImpl extends DefaultRepositoryImpl<RescInfo,Resc> implements RescRepository {
    /**
     * AcegiCacheManager.
     */
    private AcegiCacheManager acegiCacheManager = null;

    /**
     * @param acegiCacheManager AcegiCacheManager.
     */
    public void setAcegiCacheManager(AcegiCacheManager acegiCacheManager) {
        this.acegiCacheManager = acegiCacheManager;
    }

    /**
     * @param o resource.
     */
    public void save(RescInfo resc) {
        boolean isNew = (resc.getId() == null);
        String orginString = "";
        if (!isNew) {
            Resc orginResc = (Resc) dao.getById(Resc.class,resc.getId(),true);
            orginString = orginResc.getResString();
            dao.evict(orginResc);
        }

        super.save(resc);

        if (!isNew
                && !StringUtils.equals(resc.getResString(), orginString)) {
            removeRescInCache(orginString);
        }

        saveRescInCache(resc);
    }

    /**
     * @param o resource.
     */
    public void delete(RescInfo res) {
        super.delete(res);
        removeRescInCache(res.getResString());
    }

    /**
     * 把资源保存里缓存.
     *
     * @param resc 资源
     */
    private void saveRescInCache(RescInfo resc) {
        GrantedAuthority[] authorities = AuthenticationHelper
            .convertToGrantedAuthority(resc.getRoles(), "name");
        ResourceDetails rd = new Resource(resc.getResString(),
                resc.getResType(), authorities);
        acegiCacheManager.addResource(rd);
    }

    /**
     * 从缓存里删除资源.
     *
     * @param resString 资源内容
     */
    public void removeRescInCache(String resString) {
        acegiCacheManager.removeResource(resString);
    }
}
